package com.jh.user;

import cn.jh.common.exception.ApiExceptionHandler;
import cn.jh.common.interceptor.AuthenticationHeaderInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.feign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@Configuration
@SpringBootApplication(scanBasePackages = { "com.jh.user" })
@EnableDiscoveryClient
@ImportAutoConfiguration(FeignAutoConfiguration.class)
@EnableFeignClients(basePackages = {"com.jh.user"})
@EnableCaching
public class UserStartup extends WebMvcConfigurerAdapter {

	public static void main(String[] args) {
		new SpringApplicationBuilder(UserStartup.class).run(args);
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new AuthenticationHeaderInterceptor()).addPathPatterns("/**");
	}

	@Bean
	public ApiExceptionHandler getApiExceptionHandler() {
		return new ApiExceptionHandler();
	}

	@Primary
	@Bean(name = "restTemplate")
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}

	/**
	 * 如果想使用 {@code http://{application.name}/request_uri} 方式直接请求服务的，就使用此{@code RestTemplate}。
	 * <pre>{@code
	 * @Autowired
	 * public ConstructExample(
	 *         @Qualifier("restOperations") RestTemplate restOperations) {
	 *     this.restOperations = restOperations;
	 * }
	 *
	 * public void doSomething() {
	 *     // notice -> application -> "spring.application.name"
	 *     restOperations.getForEntity("http://notice/v1.0/notice/do_something", String.class);
	 * }
	 * }</pre>
	 */
	@Bean(name = "restOperations")
	@LoadBalanced
	public RestTemplate loadBalanceRestTemplate() {
		return new RestTemplate();
	}
}
